"use strict";
cc._RF.push(module, 'a6b41+4f8RGar4J++XrrMSb', 'UserUI');
// scripts/mainScene/UserUI.js

"use strict";

/**
 * 主界面
 * 用户信息界面
 */

var OrderStatus = cc.Enum({
    All: 0, //全部订单
    Wait: 1, //待开奖订单
    Win: 2 //中奖订单
});

cc.Class({
    extends: cc.Component,

    properties: {
        labName: cc.Label, //用户名字
        labCommonUser: cc.Label, //普遍用户或vip
        labBalance: cc.Label, //余额
        spCommon1: cc.Node, //余额背景图
        spUserHead: cc.Sprite, //用户头像
        spBaseHead: cc.SpriteFrame, //默认游客头像图片
        toggleGruop: [cc.Toggle], //订单数组
        orderContent: [cc.Node], //订单scrollview列表中content
        orderScroll: [cc.ScrollView], //订单scrollview
        ndPrompt: cc.Node, //暂无订单消息
        orderItemPrefab: cc.Prefab, //订单item
        userAccountRecordPop: cc.Prefab, //账变记录预制
        userSettingPop: cc.Prefab, //设置预制
        userBackWaterPop: cc.Prefab, //我的回水预制
        userWithDrawPop: cc.Prefab, //提现预制
        userEarningPop: cc.Prefab, //我的收益预制
        userOrderDetil: cc.Prefab, //订单详情预制

        _indexPageNumber: [], //页 
        _indexRowsPerPage: [], //行
        _isopen: false,
        isNowRefreshing: false //是否正在加载新列表

    },

    onLoad: function onLoad() {
        window.Notification.on("updateUserUI", function (data) {
            this.resetRefresh(0);
        }, this);
    },

    // use this for initialization
    start: function start() {

        //订单单选按钮添加按钮事件
        for (var i = 0; i < this.toggleGruop.length; i++) {
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node;
            checkEventHandler.component = "UserUI";
            checkEventHandler.handler = "onOrderChange";
            checkEventHandler.customEventData = i;
            this.toggleGruop[i].getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        }

        this.labCommonUser.string = '普通用户';
        this.labBalance.string = User.getGoldBean() + '元宝';
        this.labName.string = User.getNickName();

        this.spUserHead.getComponent(cc.Sprite).spriteFrame = this.spBaseHead;
        this.spUserHead.node.width = 180;
        this.spUserHead.node.height = 180;
    },

    resetRefresh: function resetRefresh(value) {
        this._indexPageNumber = [1, 1, 1, 1];
        this._indexRowsPerPage = [11, 11, 11, 11];
        //数据初始化
        this.requestRefresh(value);
    },

    //获取服务器信息刷新
    requestRefresh: function requestRefresh(value) {
        this.labCommonUser.string = '';
        this.labBalance.string = '0元宝';
        this.spUserHead.getComponent(cc.Sprite).spriteFrame = this.spBaseHead;
        this.spUserHead.node.width = 180;
        this.spUserHead.node.height = 180;
        this.labName.string = '';

        var recv = function recv(ret) {
            ComponentsUtils.unblock();
            if (ret.Code !== 0) {
                cc.error(ret.Msg);
            } else {
                //对返回数据做安全处理
                if (!Utils.isEffective(ret.Data)) {
                    return;
                }

                if (this._isopen == false) {
                    this._isopen = true;
                    User.setUserCode(ret.Data.UserCode);
                }

                User.setNickName(ret.Data.Nick);
                User.setTel(ret.Data.Mobie);
                User.setBalance(ret.Data.Balance);
                User.setGoldBean(ret.Data.Gold);
                User.setIsrobot(ret.Data.IsRobot);
                User.setAvataraddress(ret.Data.AvatarUrl);
                User.setVipLevel(ret.Data.VIP);
                User.setFullName(ret.Data.FullName);
                User.setIsCertification(ret.Data.IsCertification);
                User.setLoginToken(ret.Data.Token);
                User.setIsWithdrawPwd(ret.Data.IsWithdrawPwd);
            }

            this.labName.string = User.getNickName();
            if (User.getVipLevel() > 0) {
                //this.labCommonUser.string = User.getVipLevel();
            } else {
                this.labCommonUser.string = '普遍用户';
            }
            this.labBalance.string = "余额     " + User.getBalance().toFixed(2) + "元宝";
            //cc.log("userui: 刷新后金额：" + this.labBalance.string);
            //根据余额这个节点的长度，让余额背景图的长度与其相适应
            this.spCommon1.width = this.labBalance.node.width + 35;

            //头像动态加载
            var url = User.getAvataraddress();
            // cc.log("init my logo1:"+url);
            if (url != "" && url != null && typeof url != "undefined") {
                //  cc.log("init my logo2:"+url);
                cc.loader.load({ url: url, type: "jpg" }, function (err, tex) {
                    //   cc.log("init my logo3:"+tex);
                    if (tex != null) {
                        var sf = new cc.SpriteFrame(tex);
                        this.spUserHead.getComponent(cc.Sprite).spriteFrame = sf;
                        this.spUserHead.node.width = 180;
                        this.spUserHead.node.height = 180;
                    } else {
                        this.spUserHead.getComponent(cc.Sprite).spriteFrame = this.spBaseHead;
                        this.spUserHead.node.width = 180;
                        this.spUserHead.node.height = 180;
                    }
                }.bind(this));
            } else {
                this.spUserHead.getComponent(cc.Sprite).spriteFrame = this.spBaseHead;
                this.spUserHead.node.width = 180;
                this.spUserHead.node.height = 180;
            }

            //订单
            for (var i = 0; i < this.toggleGruop.length; i++) {
                if (i == value) {
                    this.toggleGruop[i].getComponent(cc.Toggle).isChecked = true;
                    this.changeOrder(i);
                } else {
                    this.toggleGruop[i].getComponent(cc.Toggle).isChecked = false;
                }
            }
        }.bind(this);

        var data = {
            Token: User.getLoginToken(),
            UserCode: User.getUserCode()
        };
        CL.HTTP.sendRequestRet(DEFINE.HTTP_MESSAGE.GETUSERINFO, data, recv.bind(this), "POST");
        ComponentsUtils.block();
    },

    onOrderChange: function onOrderChange(toggle, customEventData) {
        if (toggle.getComponent(cc.Toggle).isChecked) {
            this.changeOrder(customEventData);
        }
    },

    //切换订单页
    changeOrder: function changeOrder(index) {
        var idx = index;
        this.ndPrompt.active = false;
        this.orderTime = "";
        this.orderContent[index].removeAllChildren();
        this.orderScroll[index].scrollToTop(0.1);
        var recv = function recv(ret) {
            this._indexPageNumber[idx] = 2;
            if (ret.Code == 0 || ret.Code == 49) {
                var obj = ret.Data;
                if (obj == null || obj.length <= 0) {
                    this.ndPrompt.active = true;
                    ComponentsUtils.unblock();
                    return;
                } else {
                    this.ndPrompt.active = false;
                }
                var month = 0;
                var day = 0;
                var show = true;
                var temp = this.orderTime == "" ? "" : this.orderTime;
                for (var i = 0; i < obj.length; i++) {
                    var time = obj[i].OrderTime;
                    var year = time.slice(0, 4);
                    var month = time.slice(4, 6);
                    var day = time.slice(6, 8);
                    if (temp == "") {
                        temp = month + day;
                    }
                    this.orderTime = temp;
                    var item = cc.instantiate(this.orderItemPrefab);
                    item.getComponent('user_order_item').init({
                        LotteryName: obj[i].LotteryName,
                        State: obj[i].OrderStatus,
                        Money: LotteryUtils.moneytoServer(obj[i].Amount),
                        Month: month,
                        Day: day,
                        Year: year,
                        type: LotteryUtils.getOrderByBuyType(obj[i].BuyType),
                        IsuseNum: obj[i].IsuseNum
                    });
                    var clickEventHandler = new cc.Component.EventHandler();
                    clickEventHandler.target = this.node;
                    clickEventHandler.component = "UserUI";
                    clickEventHandler.handler = "onClickCallBack";
                    clickEventHandler.customEventData = { code: obj[i].OrderCode, type: obj[i].BuyType };
                    item.getComponent(cc.Button).clickEvents.push(clickEventHandler);

                    this.orderContent[index].addChild(item);
                }
            } else {
                ComponentsUtils.showTips(ret.Msg);
            }
            ComponentsUtils.unblock();
        }.bind(this);

        var data = {
            Token: User.getLoginToken(),
            UserCode: User.getUserCode(),
            OrderStatus: idx,
            PageNumber: 1,
            RowsPerPage: 11
        };
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETORDERRECORDLIST, data, recv.bind(this), "POST");
        ComponentsUtils.block();
    },

    //订单列表回调
    onClickCallBack: function onClickCallBack(event, customEventData) {
        if (customEventData.type == 0 || customEventData.type == 2) {
            var recv = function recv(ret) {
                ComponentsUtils.unblock();
                if (ret.Code == 0) {
                    var canvas = cc.find("Canvas");
                    var userOrderDetil = cc.instantiate(this.userOrderDetil);
                    userOrderDetil.getComponent('user_order_detail_pop').init(ret.Data, 0, customEventData.code, 0);
                    canvas.addChild(userOrderDetil);
                } else {
                    ComponentsUtils.showTips(ret.Msg);
                }
            }.bind(this);
            var data = {
                Token: User.getLoginToken(),
                UserCode: User.getUserCode(),
                OrderCode: customEventData.code,
                SchemeDetail: ""
            };
            CL.HTTP.sendRequestRet(DEFINE.HTTP_MESSAGE.GETORDERDETAILS, data, recv.bind(this), "POST");
            ComponentsUtils.block();
        }
    },

    //滚动获取下一页
    scrollCallBack: function scrollCallBack(scrollview, eventType, customEventData) {
        if (eventType === cc.ScrollView.EventType.BOUNCE_BOTTOM) {
            //下拉刷新,当底部的offset抵达到某个点的时候
            var offset_y = scrollview.getScrollOffset().y;
            var max_y = scrollview.getMaxScrollOffset().y;
            if (offset_y - max_y > 200) {
                if (this.isNowRefreshing == false) {
                    var custom = customEventData;
                    this.nextOrderList(this.orderContent[customEventData], custom);
                    this.isNowRefreshing = true;
                }
            }
        }
    },

    //下拉刷新
    scrollRefresh: function scrollRefresh(scrollview, eventType, customEventData) {
        if (eventType === cc.ScrollView.EventType.BOUNCE_TOP) {
            //下拉刷新,当底部的offset抵达到某个点的时候
            var offset_y = scrollview.getScrollOffset().y;
            var max_y = scrollview.getMaxScrollOffset().y;
            if (max_y - offset_y > 200) {
                this.resetRefresh(customEventData);
            }
        }
    },

    //加载下一页信息
    nextOrderList: function nextOrderList(rootLayer, index) {
        var self = this;
        var content = rootLayer;
        var recv = function recv(ret) {
            if (ret.Code == 0) {
                var obj = ret.Data;
                if (obj == null || obj.length <= 0) {
                    this.node.runAction(cc.sequence(cc.delayTime(2), cc.callFunc(function () {
                        this.isNowRefreshing = false;
                    }.bind(this))));
                    ComponentsUtils.unblock();
                    return;
                }

                var month = 0;
                var day = 0;
                var show = true;
                var temp = this.orderTime == "" ? "" : this.orderTime;
                for (var i = 0; i < obj.length; i++) {
                    var time = obj[i].OrderTime;
                    var year = time.slice(0, 4);
                    var month = time.slice(4, 6);
                    var day = time.slice(6, 8);
                    if (temp == "") {
                        temp = month + day;
                    }
                    this.orderTime = temp;
                    var item = cc.instantiate(self.orderItemPrefab);
                    item.getComponent('user_order_item').init({
                        LotteryName: obj[i].LotteryName,
                        State: obj[i].OrderStatus,
                        Money: LotteryUtils.moneytoServer(obj[i].Amount),
                        Month: month,
                        Day: day,
                        Year: year,
                        type: LotteryUtils.getOrderByBuyType(obj[i].BuyType),
                        IsuseNum: obj[i].IsuseNum
                    });
                    var clickEventHandler = new cc.Component.EventHandler();
                    clickEventHandler.target = this.node;
                    clickEventHandler.component = "UserUI";
                    clickEventHandler.handler = "onClickCallBack";
                    clickEventHandler.customEventData = { code: obj[i].OrderCode, type: obj[i].BuyType };
                    item.getComponent(cc.Button).clickEvents.push(clickEventHandler);
                    content.addChild(item);
                }
                this._indexPageNumber[index] += 1;
            } else {
                ComponentsUtils.showTips(ret.Msg);
            }
            this.isNowRefreshing = false;
            ComponentsUtils.unblock();
        }.bind(this);

        var data = {
            Token: User.getLoginToken(),
            UserCode: User.getUserCode(),
            OrderStatus: index,
            PageNumber: this._indexPageNumber[index],
            RowsPerPage: this._indexRowsPerPage[index]
        };
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETORDERRECORDLIST, data, recv.bind(this), "POST");
        ComponentsUtils.block();
    },

    //前往账变记录
    onGotoAccountRecordBtn: function onGotoAccountRecordBtn(event) {
        var canvas = cc.find("Canvas");
        var userAccountRecord = cc.instantiate(this.userAccountRecordPop);
        userAccountRecord.getComponent('user_accountRecord_pop').init(event.target.parent.getComponent(cc.Toggle));
        canvas.addChild(userAccountRecord);
    },

    //提现
    onWithDraw: function onWithDraw(event) {
        var canvas = cc.find("Canvas");
        // if(User.getIsCertification())//实名制
        // {
        //     if(User.getIsWithdrawPwd())//是否存在提现密码
        //     {
        var userGetBankCash = cc.instantiate(this.userWithDrawPop);
        userGetBankCash.getComponent('user_getBankCash_pop').init(event.target.parent.getComponent(cc.Toggle));
        canvas.addChild(userGetBankCash);

        //     }
        //     else
        //     {   
        //         this.onCashPasswordBtn();
        //     }
        // }
        // else
        // {
        //     this.onGotoVerifiedBtn();
        // }   
    },

    //我的回水
    onGotoBackWater: function onGotoBackWater(event) {
        var canvas = cc.find('Canvas');
        var userBackWaterPop = cc.instantiate(this.userBackWaterPop);
        userBackWaterPop.getComponent(userBackWaterPop.name).init(event.target.parent.getComponent(cc.Toggle));
        canvas.addChild(userBackWaterPop);
    },

    //我的收益
    onGotoEarning: function onGotoEarning(event) {
        var canvas = cc.find('Canvas');
        var userEarningPop = cc.instantiate(this.userEarningPop);
        userEarningPop.getComponent(userEarningPop.name).init(event.target.parent.getComponent(cc.Toggle));
        canvas.addChild(userEarningPop);
    },

    //设置
    onSetting: function onSetting() {
        var canvas = cc.find("Canvas");
        var userSetting = cc.instantiate(this.userSettingPop);
        canvas.addChild(userSetting);
    },

    onDestroy: function onDestroy() {
        window.Notification.offType("updateUserUI");
    }

});

cc._RF.pop();